﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Cinser.DataTranslate
{
    public class OracleTranslateDal : TranslateDalBase
    {
        Cinser.DBUtility.DAL.OracleDALCommon dal;

        public OracleTranslateDal(string connStr)
        {
            dal = new Cinser.DBUtility.DAL.OracleDALCommon(connStr);
        }

        public override DataTable GetDataList(string tbName, string sqlWhere = "1=1")
        {
            return dal.GetDataList(tbName, sqlWhere);
        }

        public override bool Add(string tbName, DataRow dr)
        {
            List<string> keys = dal.GetKeyColumns(tbName);
            return Add(tbName, dr, keys.ToArray());
        }

        public override bool Add(string tbName, DataRow dr, string[] keysColumns)
        {
            List<string> keys = keysColumns.ToList();
            List<string> keysValue = new List<string>();
            foreach (var item in keys)
            {
                keysValue.Add(dr[item].ToString());
            }
            if (dal.IsExist(tbName, keys.ToArray(), keysValue.ToArray()))
            {
                dal.Update(tbName, dr, keys.ToArray(), keysValue.ToArray());
            }
            else
            {
                dal.Add(tbName, dr);
            }
            return true;
        }

        public override List<string> GetAllTableNames()
        {
            return dal.GetTableNames();
        }

        public override bool Update(string tbName, DataRow dr, string[] keysColumns, string[] keyValues)
        {
            dal.Update(tbName, dr, keysColumns, keyValues);
            return true;
        }

        public override bool IsExistTable(string tbName)
        {
            return dal.IsExistTable(tbName);
        }

        public override List<string> GetColumns(string tbName)
        {
            List<string> list = new List<string>();
            DataTable dt = dal.GetTableColumns(tbName);
            if (dt != null && dt.Columns.Count > 0)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    list.Add(dt.Columns[i].ColumnName);
                }
            }
            return list;
        }
    }
}
